<template>
  <div id="app">

    <template v-if=" uistate.adminid==-1 ">
      <login  />
    </template>

    <template v-else>
      <el-container>
        <el-header>
          <el-menu
            class="el-menu-demo"
            mode="horizontal"
            :router="true"
            :default-active="activeIndex"
            @select="handleSelect"
            background-color="#393D49"
            text-color="#fff"
            active-text-color="#fff"
            >
            <el-menu-item v-for="(nav, index) in navs" :key="index" :route="nav" :index="nav.name">
                <img class="head-icon" :src="nav.icon"/><span class="menu-text">{{ nav.title }}<div v-if="nav.name==='home' && badge" class="badge"></div></span>
            </el-menu-item>
            <el-submenu index="null" style="float:right">
              <template slot="title"><i class="el-icon-user-solid"></i>设置</template>
              <div style="background-color: #393d49;color:#fff" class="el-menu-item" @click="$modal.show('changePassDialog')">修改密码</div>
              <div style="background-color: #393d49;color:#fff" class="el-menu-item" @click="logoutSystem">退出登录</div>
            </el-submenu>
          </el-menu>
        </el-header>
        <el-main>
          <router-view/>
        </el-main>
      </el-container>
      <modal name="changePassDialog"
        transition="nice-modal-fade"
        overlayTransition="overlay-fade"
        draggable=".el-card__header" :width="372" height="auto">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="display: flex; flex-direction: row;justify-content: space-between;">
            <span>修改密码</span>
            <i class="el-icon-close" @click.stop="$modal.hide('changePassDialog')"></i>
          </div>
          <div>
            <el-form ref="form" :model="passForm" label-width="0">
              <el-form-item label="">
              <el-input placeholder="请输入原密码" v-model="oldPass" show-password></el-input>
              </el-form-item>
              <el-form-item label="">
              <el-input placeholder="请输入新密码" v-model="newPass" show-password></el-input>
              </el-form-item>
              <el-form-item label="">
              <el-input placeholder="请确认新密码" v-model="verPass" show-password></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="changePass">立即修改</el-button>
                <el-button @click.stop="$modal.hide('changePassDialog')">取消</el-button>
              </el-form-item>
            </el-form>
          </div>

        </el-card>

      </modal>

    </template>

  </div>
</template>
<script>
import Vue from 'vue';
import { mapState, mapActions, mapMutations } from 'vuex';
import '@/assets/layui/layui.all.js';
import '@/assets/layui/css/layui.css';
import '@/assets/layui/css/modules/layer/default/layer.css';
import '@/assets/layui/css/modules/laydate/default/laydate.css';
import CustomDialog from '@/components/customDialog';
import login from '@/views/login'


export default {
  data() {
    return {
      passForm:{
      },
      oldPass:'',
      newPass:'',
      verPass:'',
      changePassDialog:false,
      subnames:[

      ],
      navs:[
        {
          name:'home',
          path:'/',
          title:'客服',
          icon:require('./assets/images/kefu.png')
        },
        {
          name:'groupsend',
          path:'/groupsend',
          title:'群发',
          icon:require('./assets/images/send.png')
        },
        {
          name:'addfriend',
          path:'/addfriend',
          title:'加好友',
          icon:require('./assets/images/add_friends.png')
        },
        {
          name:'marketing',
          path:'/marketing',
          title:'营销',
          icon:require('./assets/images/yingxiao.png')
        },
        {
          name:'moments',
          path:'/moments',
          title:'朋友圈',
          icon:require('./assets/images/moment.png')
        },
        {
          name:'groupmanage',
          path:'/groupmanage',
          title:'群管理',
          icon:require('./assets/images/group_manage.png')
        },
        // {
        //   name:'statistics',
        //   path:'/statistics',
        //   title:'统计',
        //   icon:require('./assets/images/tongji.png')
        // },
        // {
        //   name:'contact',
        //   path:'/contact',
        //   title:'通讯录',
        //   icon:require('./assets/images/addressbook.png')
        // }
      ]

    }
  },
  components:{login,CustomDialog},
  mounted() {

  },
  computed: {
    ...mapState(['manager','websocket','uistate','accountMap','chatMap','chatMapList']),
    activeIndex(){
      const match = this.$route.matched[0] || this.$route;
      const name = match.path.replace('/', '')

      const nav = this.navs.filter(nav=>{
        return nav.name===name
      })[0]

      return nav?nav.name:'home'
    },
    badge(){
      return Object.values(this.accountMap).reduce((total,item)=>total+ +item.noReadCnt,0)
    }
  },

  watch: {

    websocket(val,oldVal){
      if(val === false && oldVal){
        this.notice({title:'与服务器断开链接，是否重连？',body:'点击查看' })
        this.$confirm('与服务器断开链接，是否重连？', '提示', {
          confirmButtonText: '立即重连',
          showClose:false,
          closeOnClickModal:false,
          showCancelButton:false,
          type: 'warning',
          center: true
        }).then(() => {
          this.initWebSocket({user_id:this.manager.id})
        }).catch(() => {
        });
      }else if(val && oldVal === false){
        this.$message({
          showClose: true,
          message: '已链接服务器',
          type: 'success'
        });

      }


    },
    uistate(newuistate,olduistate){
      if(newuistate.accountid !== olduistate.accountid){
        const wxaccount = this.accountMap[newuistate.accountid].wxid;
        const csid = newuistate.adminid;
        this.requestChatMap({csid,wxaccount})
          .then(rs=>{
            if(rs&&rs[0])
            this.updateUIState({chatid:rs[0].id})
          })
        this.requestFriendMap({csid,wxaccount})

        this.updateUIState({chatid:-1})

      }
      if(newuistate.chatid&&newuistate.chatid!==olduistate.chatid && newuistate.chatid!==-1){
        const wxaccount = this.accountMap[newuistate.accountid].wxid;
        const csid = newuistate.adminid;
        const friendid = this.chatMap[newuistate.chatid].friendwxid;
        const params = {
          accountWxId:wxaccount,
          chatid:newuistate.chatid,
          friendWxid:friendid,
          csId:csid,pageNo:1,pageSize:20 }
        this.requestMessageMap(params).then(()=>this.sendChatReaded({
          csId:csid, wxAccount:wxaccount, friendAccount:friendid
        }))
        const groupid = friendid.endsWith('@chatroom')?friendid:false
        if(groupid){
          this.requestGroupMember({
            csId:csid,wxAccount:wxaccount,groupNo:groupid
          })
        }

        console.log('groupid',groupid)
      }
    },

  },
  methods: {
    ...mapActions(['init','initWebSocket','requestChatMap','requestMessageMap','requestFriendMap','requestGroupMember','notice','sendChatReaded','logout']),
    ...mapMutations(['updateUIState']),
    logoutSystem(){
      this.$confirm('是否退出登陆？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout()
      }).catch(() => {
      });

    },
    changePass(){
      if(this.uistate.adminid === -1)return this.$msg('未登录')
      if(this.oldPass === '')return this.$msg('请输入老密码')
      if(this.newPass === '')return this.$msg('请输入新密码')
      if(this.verPass === '')return this.$msg('请确认新密码')
      if(this.newPass !== this.verPass)return this.$msg('两次新密码输入不一致')
      const params = {
        csId:this.uistate.adminid,
        oldPass:this.oldPass,
        newPass:this.newPass,
      }
      this.$api.user.updatePass(params)
        .then(data=>{
          this.logout()
          this.$modal.hide('changePassDialog')
        })
        .catch(e=>this.$msg(e))


    },
    handleSelect(key, keyPath){
      console.log(key, keyPath)
    },
    contextmenuclick(e){
      console.log(e)
    }

  }
}
</script>
<style>
@import url("../css/index.css");
#app {
  height: 100%;
  user-select: none;
}
.setting{
  float:right
}
.setting:hover .layui-nav-child{
  display: block;
  top:60px;
  left:-20px;
}

#app .el-container{
  height: 100%;
}
.el-header{
  background-color: #393d49
}

#app .el-main{
  padding: 0;
}
.head-icon{
  width: 20px;
  height: 20px;
  vertical-align: text-bottom;
  margin-right: 5px;
}
.menu-text{
  position: relative;
}
.badge{
  position: absolute;
  width: 8px;
  height: 8px;
  background: #F56C6C;
  top: 0;
  right: -4px;
  border-radius: 4px;
}
</style>
